import {getStorage} from '@/utils/wxapi.js'
const url = 'http://beta.jxc4.com'
let token
getStorage('token').then(res => {
  token = res
})

const $ajax = params => new Promise((resolve, reject) => {
  wx.showNavigationBarLoading()
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  wx.request({
    url: url + params.url,
    data: params.data,
    header: {
      'Content-Type': 'application/json',
      'token': token,
      ...params.header
    },
    method: params.method,
    success: function (res) {
      if (res.data.code === '0') {
        // 成功
        resolve(res.data)
      } else {
        // 失败
        wx.showToast({
          title: res.data.desc,
          icon: 'none',
          duration: 4000
        })
      }
      wx.hideNavigationBarLoading()
    },
    fail: function (e) {
      wx.showToast({
        title: e.errMsg,
        icon: 'none',
        duration: 4000
      })
      wx.hideNavigationBarLoading()
      reject(e)
    },
    complete: () => {
      setTimeout(() => {
        wx.hideLoading()
      }, 1000)
    }
  })
})

export {$ajax}
